package com.gmt.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @author John.zhang
 * @version Id: SecurityConfig, v 1.0 2020/11/12 19:16 ZhiYong Exp $
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置自定义的账号密码
        /*auth.inMemoryAuthentication()
                .withUser("root")
                .password("{noop}root")
                .roles("roleA");*/

        //数据库认证
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                // 指定自定义的登录界面
                .loginPage("/login.html")
                // 必须和登录表单的 action一致
                .loginProcessingUrl("/login.do")
                .and()
                // 定义哪些资源被保护
                .authorizeRequests()
                .antMatchers("/login.html")
                // login.html可以匿名访问
                .permitAll()
                .anyRequest()
                //出来登录页面其他都需要认证
                .authenticated();
        // 禁用跨越攻击
        http.csrf().disable();
    }


    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode("guest"));
    }

}
